package com.hongdee.scm.enterwarehouse.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.enterwarehouse.dao.ITScmEnterWareHouseDao;
import com.hongdee.scm.enterwarehouse.entity.TScmEnterWareHouse;
import com.hongdee.scm.enterwarehouse.service.ITScmEnterWareHouseService;
import com.hongdee.scm.monthlybalance.service.ITScmMonthlyBalanceService;
import com.hongdee.scm.stock.dao.ITScmStockDao;
import com.hongdee.scm.stock.entity.TScmStock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mr. Xu on 2017/5/5.
 */
@Service
public class TScmEnterWareHouseServiceImpl implements ITScmEnterWareHouseService {

    String entityName = "TScmEnterWarehouse";

    @Autowired
    private ITScmEnterWareHouseDao itScmEnterWareHouseDao;
    @Autowired
    private ITScmStockDao itScmStockDao;
    @Autowired
    private ITScmMonthlyBalanceService itScmMonthlyBalanceService;
    /**
     * 更新打印状态
     * @param id
     * @param uid
     * @throws Exception
     */
    @Override
    public void update(String id, String uid) throws Exception {

        Map params = new HashMap();
        String hql = "update " + entityName + " set printStatus ='1' where id =:id and company_id =:companyId";
        params.put("id", id);
        params.put("companyId", TokenUtil.getCompanyId(uid));
        this.itScmEnterWareHouseDao.update(hql, params);
    }

    /**
     * 车辆未入库（验车单)
     *
     * @param uid
     * @param start
     * @param limit
     * @return
     * @throws Exception
     */
    @Override
    public Map notEnterWareHouse(Map data, String start, String limit, String uid) throws Exception {
        List params = new ArrayList();
        StringBuffer sql = new StringBuffer();
        //调拨
        StringBuffer allocationSql = new StringBuffer();
        //采购
        StringBuffer purchaseSql = new StringBuffer();
        String enterTypeSql = " union all ";
        //采购未入库
        purchaseSql.append(" SELECT '采购未入库' enterType,'' as allocation_order_id,'' tempVin,'' allocation_date,'' as aim_warehouse, ")
                .append(" '' arrive_warehouse_date,tsc.*,tbm.model_name,tcc.configure_name FROM t_scm_car tsc  ")
                .append(" LEFT JOIN t_bc_carmodel tbm ON tsc.car_model_id = tbm.id ")
                .append(" LEFT JOIN t_bc_carconfigure tcc ON tsc.configure_id = tcc.id ")
                .append(" where `status`='0' and company_id = ? ");
        //调拨未入库
        allocationSql.append(" SELECT temp2.*,tsc.*,tbm.model_name,tcc.configure_name ")
                .append(" FROM (SELECT * FROM ( SELECT '调拨未入库' enterType,temp.allocation_order_id, ")
                .append("temp.vin as tempVin,max(tsao.allocation_date) AS allocation_date, ")
                .append("tsao.aim_warehouse,tsao.arrive_warehouse_date FROM ( SELECT * FROM t_scm_allocation_order_detail ")
                .append("WHERE vin IN (SELECT vin FROM t_scm_car)  ORDER BY vin ) temp ")
                .append("LEFT JOIN t_scm_allocation_order tsao ON temp.allocation_order_id = tsao.id ")
                .append("GROUP BY temp.vin ) temp1 WHERE temp1.aim_warehouse IN ( SELECT id ")
                .append("FROM t_scm_warehouse WHERE company_id = ? ) ) temp2 ")
                .append(" left join t_scm_car tsc on temp2.tempVin=tsc.vin ")
                .append(" LEFT JOIN t_bc_carmodel tbm ON tsc.car_model_id = tbm.id ")
                .append(" LEFT JOIN t_bc_carconfigure tcc ON tsc.configure_id = tcc.id ")
                .append("WHERE  temp2.tempVin ")
                .append("NOT IN ( SELECT vin FROM t_scm_stock WHERE warehouse_id IN ( ")
                .append("SELECT id FROM t_scm_warehouse WHERE company_id = ? ) ) ");
        //入库类型不为空
        if (data.get("enterType") != null && !data.get("enterType").equals("")) {
            //采购入库
            if (data.get("enterType").equals("0")) {
                sql.append(purchaseSql);
                params.add(TokenUtil.getCompanyId(uid));
            }
            //调拨入库
            if (data.get("enterType").equals("1")) {
                sql.append(allocationSql);
                params.add(TokenUtil.getCompanyId(uid));
                params.add(TokenUtil.getCompanyId(uid));
            }
        }else{
            sql.append("select * from ( ");
            sql.append(purchaseSql+enterTypeSql+allocationSql);
            sql.append(" ) allsql ");
            params.add(TokenUtil.getCompanyId(uid));
            params.add(TokenUtil.getCompanyId(uid));
            params.add(TokenUtil.getCompanyId(uid));
        }
        return this.itScmEnterWareHouseDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 更新车辆打印状态
     * @param vins 车架号数组
     * @throws Exception
     */
    @Override
    public void updateValidateStatus(String[] vins) throws Exception {

        StringBuffer hql = new StringBuffer();
        hql.append("update T_Scm_Car set finance_type = '1',sale_type='1',update_time=? ");
        List params = new ArrayList();
        params.add(System.currentTimeMillis());
        if (vins.length > 0) {
            hql.append(" where vin in ( ");
            for (Object vin : vins) {
                hql.append(" ? , ");
                params.add(vin);
            }
            hql.append(" '' ) ");
        }
        hql.append(" and finance_type='0'");
        this.itScmEnterWareHouseDao.executeSQL(hql.toString(), params.toArray());
    }

    //确认回库
    @Override
    public void confirmBack (Map data ,String uid) throws Exception{
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        //Date d = new Date();
        //String date = sdf.format(d);
        int result = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).compareTo(data.get("aimhouseDate").toString());
        if(result<0){
           throw new Exception("不能选择将来日期");
        }
        if(itScmMonthlyBalanceService.ifMonthlyBalance(TokenUtil.getCompanyId(uid),new SimpleDateFormat("yyyy-MM-dd").parse(data.get("aimhouseDate").toString()))){
            Calendar lastDate = Calendar.getInstance();
            lastDate.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(data.get("aimhouseDate").toString()));
            lastDate.set(Calendar.DATE, 1);
            lastDate.add(Calendar.MONTH, 1);
            lastDate.add(Calendar.DATE, -1);
            String format = new SimpleDateFormat("yyyy-MM-dd").format(lastDate.getTime());
            throw new Exception("已月结或月结中,不能车辆入库,请输入"+format+"之后的日期");
        }

        List<String> list = new ArrayList<>();
        list = (List<String>) data.get("id");
        for (String id: list) {
            if(!"".equals(id)){
                //查询将确认回库的车辆的信息
                TScmStock entity = new TScmStock();
                //查询该车辆对应的属性
                Map map = itScmStockDao.info("select status,vin, id, company_id,brand from t_scm_car where id = ?",id);
                //查看该车辆是否一在库存中
                List l = this.itScmEnterWareHouseDao.list("select * from t_scm_stock where vin = ? and company_id =?",map.get("vin"),TokenUtil.getCompanyId(uid));
                if(l.size()>0){
                  throw new Exception(map.get("vin")+"该车已在库中！");
                }
                this.itScmEnterWareHouseDao.executeSQL("update t_scm_car set status='1' where id = ? ",id);
                //入库类型
                if(this.itScmEnterWareHouseDao.list("select * from t_scm_sale_order_detail where car_id=? and status='1'",id).size()>0){
                    entity.setEnterType("2");//已售入库
                }
                if(this.itScmEnterWareHouseDao.list("select * from T_Scm_OutWareHouse where car_id=? and outType='2' and out_status<>'2' and need_back='0'",id).size()>0){//调拨入库
                    this.itScmEnterWareHouseDao.executeSQL("delete from t_scm_stock where car_id=?",id);
                    entity.setEnterType("3");
                }
                this.itScmEnterWareHouseDao.executeSQL("update T_Scm_OutWareHouse set out_status='2' where out_status='1' and need_back='0' and car_id = ? ",id);
                //入库时间
                entity.setEnterDate(data.get("aimhouseDate").toString());
                //vin
                entity.setVin(map.get("vin").toString());
                entity.setCarId(map.get("id").toString());
                //仓库id
                entity.setWarehouseId(data.get("aimWhereHouse").toString());
                //单位id
                entity.setCompanyId(map.get("companyId").toString());
                /* zhc注释20170720 存ID没必要，不写入了
                //车型
                entity.setCarModel(map.get("car_model_id").toString());
                //配置
                entity.setConfigureName(map.get("configure_id").toString());
                //车系
                entity.setCarSeries(map.get("car_series_id").toString());
                //销售类型
                entity.setSaleType("1"); */
                //品牌
                if(map.get("brand")!=null&&!map.get("brand").equals("")){
                    entity.setBrand(map.get("brand").toString());
                }
                //创建时间
                entity.setCreateTime(Calendar.getInstance().getTimeInMillis());
                //创建人
                entity.setCreateUser(uid);
                //调拨锁定
                entity.setAllocationStatus("0");
                //更新库存表
                this.itScmStockDao.saveOrUpdate(entity);

                TScmEnterWareHouse inRecord = new TScmEnterWareHouse();
                inRecord.setCreateUser(uid);
                inRecord.setCreateTime(Calendar.getInstance().getTimeInMillis());
                inRecord.setCarId(entity.getCarId());
                inRecord.setVin(entity.getVin());
                inRecord.setCompanyId(entity.getCompanyId());
                inRecord.setEnterType(entity.getEnterType());
                inRecord.setEnterDate(entity.getEnterDate());
                this.itScmStockDao.saveOrUpdate(inRecord);

            }else {
                throw new Exception("请选择车辆！");
            }
        }

    }
}
